package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constants.WmNewsConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAuditService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@EnableAsync
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsAuditService wmNewsAuditService;




    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //2.2 根据关键字查询
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //2.3 根据频道id查询
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //2.4 根据开始和结束时间查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }

        //2.5 根据登录用户id查询
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = super.page(page, queryWrapper);

        //3.返回数据结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 保存-修改-提交草稿为一体的方法
     * 主方法
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        List<String> imageList = dto.getImages();
        if (CollUtil.isNotEmpty(imageList)) {
            String images = String.join(",", imageList);
            wmNews.setImages(images);
        }

        //获取文章图片
        List<String> images = getImages(dto);

        //自动选择图片
        images = AutoSelectImages(dto, images, wmNews);

        //新增文章、草稿或修改文章
        saveOrUpdateArticle(dto,wmNews);

        //保存图片与文章关系
        saveTheImage(dto, images, wmNews);

        //异步调用自动审核
        wmNewsAuditService.WmNewsAudit(wmNews.getId().longValue());

        //6.返回数据
        return ResponseResult.okResult("发布文章完成");
    }

    /**
     * 自动选择图片
     * @param dto
     * @param images
     * @param wmNews
     * @return
     */
    private static List<String> AutoSelectImages(WmNewsDto dto, List<String> images, WmNews wmNews) {
        if(dto.getType().equals(WmNewsConstants.LAYOUT_AUTO)){
            if(images.size() == 0){
                wmNews.setType(WmNewsConstants.LAYOUT_NONE);
            } else if (images.size() >=1 && images.size() <3) {
                Collections.shuffle(images);
                images= images.stream()
                        .limit(1)
                        .collect(Collectors.toList());
                wmNews.setImages(String.join(",",images));
                wmNews.setType(WmNewsConstants.LAYOUT_SINGLE);
            } else if (images.size()>=3) {
                Collections.shuffle(images);
                 images = images.stream()
                        .limit(3)
                        .collect(Collectors.toList());
                wmNews.setImages(String.join(",",images));
                wmNews.setType(WmNewsConstants.LAYOUT_MANY);
            }
        }else{
            images = dto.getImages();
        }
        return images;
    }

    /**
     * 获取图片
     * @param dto
     * @return
     */
    private static List<String> getImages(WmNewsDto dto) {
        List<String> images = new ArrayList<>();
        List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                String image = map.get("value").toString();
                images.add(image);
            }
        }
        return images;
    }

    /**
     * 保存图片
     * @param dto
     * @param images
     * @param wmNews
     */
    private void saveTheImage(WmNewsDto dto, List<String> images, WmNews wmNews) {
        if(CollUtil.isNotEmpty(images)) {
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                    Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images)
            );
            List<Integer> idList = wmMaterials.stream().map(x -> x.getId()).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(idList)) {
                if(dto.getType().equals(WmNewsConstants.LAYOUT_AUTO)){
                    wmNewsMaterialMapper.saveRelations(idList, wmNews.getId(), WmNewsConstants.REFRENCE_CONTENT);
                }else {
                    wmNewsMaterialMapper.saveRelations(idList, wmNews.getId(), WmNewsConstants.REFRENCE_COVER);
                }
            }
        }
    }

    /**
     * 新增或者修改
     * @param wmNews
     */
    private void saveOrUpdateArticle(WmNewsDto dto, WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());//当前用户
        wmNews.setCreatedTime(new Date());//创建时间
        wmNews.setEnable((short) 1);//1://展示
        wmNews.setSubmitedTime(new Date());
        wmNews.setPublishTime(dto.getPublishTime());
        wmNews.setContent(dto.getContent());

        //文章
        if(dto.getId() == null){
            this.save(wmNews);
        }else{
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }

    }

    /**
     * 获取文章信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getEssayById(Long id) {
        return ResponseResult.okResult(this.getById(id));
    }


    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        WmNews wmNews = BeanUtil.toBean(dto, WmNews.class);
        this.updateById(wmNews);
        WmNews wmNewss = this.getById(wmNews.getId());
        rabbitTemplate.convertAndSend(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY,wmNewss);
        return ResponseResult.okResult("文章上下架完成");
    }
}
